/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.sistema.entidades;

import br.com.sistema.excecoes.EntidadeNaoEncontrada;
import br.com.sistema.infraestrutura.ConnectionPool;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Lauro
 */
public class Pagina {

    private int id;
    private String titulo;
    private String conteudo;
    private ItemMenu itemMenu;
    protected Connection conexao;

    public Pagina(int id, String titulo) {
        this.id = id;
        this.titulo = titulo;
    }

    public Pagina(int id) throws SQLException, EntidadeNaoEncontrada {
        this.id = id;
        buscar();
    }

    public static Pagina getPagina(int id) throws SQLException {
        try {
            return new Pagina(id);
        } catch (EntidadeNaoEncontrada ex) {
            return null;
        }
    }

    public static Pagina getPagina(ItemMenu menu) throws SQLException {
        Connection conexao = ConnectionPool.getConnection();
        PreparedStatement query = conexao.prepareStatement(getSQLBuscarPorItemMenu());
        query.setInt(1, menu.getId()); // id
        ResultSet result = query.executeQuery();
        if (result.next()) {
            return new Pagina(
                    result.getInt("id"),
                    result.getString("titulo"));
        } else {
            return null;
        }
    }

    public static List<Pagina> getPaginasSemMenu() throws SQLException {
        List<Pagina> paginas = new ArrayList<Pagina>();
        Connection conexao = ConnectionPool.getConnection();
        PreparedStatement query = conexao.prepareStatement(getSQLBuscarSemMenu());
        ResultSet result = query.executeQuery();
        while (result.next()) {
            Pagina pagina = new Pagina(
                    result.getInt("id"),
                    result.getString("titulo"));
            paginas.add(pagina);
        }
        
        return paginas;
    }

    //<editor-fold defaultstate="collapsed" desc="Metodos Getters & Setters.">
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitulo() {
        return titulo;
    }

    public void setTitulo(String titulo) {
        this.titulo = titulo;
    }

    public String getConteudo() {
        return conteudo;
    }

    public void setConteudo(String conteudo) {
        this.conteudo = conteudo;
    }

    public ItemMenu getItemMenu() {
        return itemMenu;
    }

    public void setItemMenu(ItemMenu itemMenu) {
        this.itemMenu = itemMenu;
    }

    public Connection getConexao() {
        if (conexao == null) {
            this.conexao = ConnectionPool.getConnection();
        }
        return conexao;
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Strings SQL.">
    private String getSQLInsercao() {
        StringBuilder sql = new StringBuilder();
        sql.append(" INSERT INTO pagina ( ");
        sql.append("   titulo, ");
        sql.append("   conteudo, ");
        sql.append("   item_menu ");
        sql.append(" ) VALUES ( ");
        sql.append("   ?, ");
        sql.append("   ?, ");
        sql.append("   ? ");
        sql.append(" ) ");
        return sql.toString();
    }

    private String getSQLAtualizacao() {
        StringBuilder sql = new StringBuilder();
        sql.append(" UPDATE ");
        sql.append(" pagina ");
        sql.append(" SET ");
        sql.append(" titulo=?, ");
        sql.append(" conteudo=?, ");
        sql.append(" item_menu=? ");
        sql.append(" WHERE id = ? ");
        return sql.toString();
    }

    private String getSQLExclusao() {
        StringBuilder sql = new StringBuilder();
        sql.append(" DELETE FROM ");
        sql.append(" pagina ");
        sql.append(" WHERE id = ? ");
        return sql.toString();
    }

    protected String getSQLBuscarPorId() {
        StringBuilder sql = new StringBuilder();
        sql.append(" SELECT * ");
        sql.append(" FROM pagina ");
        sql.append(" WHERE id = ? ");
        return sql.toString();
    }

    private static String getSQLBuscarSemMenu() {
        StringBuilder sql = new StringBuilder();
        sql.append(" SELECT pagina.* ");
        sql.append(" FROM pagina ");
        sql.append(" LEFT OUTER JOIN noticia ON pagina.id = noticia.id ");
        sql.append(" WHERE noticia.id IS NULL ");
        sql.append(" AND pagina.item_menu IS NULL ");
        return sql.toString();
    }

    private static String getSQLBuscarPorItemMenu() {
        StringBuilder sql = new StringBuilder();
        sql.append(" SELECT pagina.id, pagina.titulo ");
        sql.append(" FROM pagina ");
        sql.append(" WHERE item_menu = ? ");
        return sql.toString();
    }
    // </editor-fold>

    // BEGIN: CRUD
    //<editor-fold defaultstate="expanded" desc="Metodos CRUD.">
    public void buscar() throws SQLException, EntidadeNaoEncontrada {
        getConexao();
        PreparedStatement query = conexao.prepareStatement(getSQLBuscarPorId());
        query.setInt(1, this.getId()); // id
        ResultSet result = query.executeQuery();
        if (result.next()) {
            this.setId(result.getInt("id"));
            this.setTitulo(result.getString("titulo"));
            this.setConteudo(result.getString("conteudo"));
        } else {
            throw new EntidadeNaoEncontrada();
        }
    }

    public void salvar() throws SQLException {
        getConexao();
        conexao.setAutoCommit(false);
        inserir();
        conexao.commit();
    }

    protected void inserir() throws SQLException {
        PreparedStatement query = conexao.prepareStatement(getSQLInsercao(), Statement.RETURN_GENERATED_KEYS);
        query.setString(1, this.getTitulo());
        query.setString(2, this.getConteudo());
        query.setInt(3, this.getItemMenu().getId());
        query.executeUpdate();
        ResultSet result = query.getGeneratedKeys();
        result.first();
        int result_id = result.getInt(1);
        this.setId(result_id);
    }

    public void alterar() throws SQLException {
        getConexao();
        conexao.setAutoCommit(false);
        atualizar();
        conexao.commit();
    }

    protected void atualizar() throws SQLException {
        PreparedStatement query = conexao.prepareStatement(getSQLAtualizacao());
        query.setString(1, this.getTitulo());
        query.setString(2, this.getConteudo());
        query.setInt(3, this.getItemMenu().getId());
        query.setInt(4, this.getId()); // id
        query.executeUpdate();
    }

    public void remover() throws SQLException {
        getConexao();
        conexao.setAutoCommit(false);
        excluir();
        conexao.commit();
    }

    protected void excluir() throws SQLException {
        PreparedStatement query = conexao.prepareStatement(getSQLExclusao());
        query.setInt(1, this.getId()); // id
        query.executeUpdate();
    }
    // </editor-fold>
    // END: CRUD
}
